package com.yunshu.yunshuapp.xianhuo;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.kuaixun.KuaixunSubscribeActivity;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.utils.YSUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;

public class PostXianhuoActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText companyTV;
    private EditText contactTV;
    private EditText phoneTV;
//    private TextView xianhuoTV;
    private TextView channelTV;
    private TextView nameTV;

//    private EditText factoryTV;
    private TextView cityTV;
//    private EditText storehouseTV;
    private RelativeLayout kucunbiaoLayout;

    private Button postButton;
    private Button saveButton;

    private Xianhuo model = new Xianhuo();
    private Xianhuo template;

    private ImageLoader mImageLoader;
    private DisplayImageOptions options;
    private RelativeLayout xianhuoLayout;
    private RelativeLayout channelLayout;
    private RelativeLayout cityLayout;
    private RelativeLayout selectTemplateView;
    private View advertiseLayout;
    private EditText advertiseET;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_xianhuo);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBar);
        bar.setTitle("编辑发布内容");
        bar.putInActivity(this);

        initViews();
        if (YSUser.instance().getContacts() != 0){
            advertiseLayout.setVisibility(View.VISIBLE);
        }
        addListener();

        // 获取图片加载实例
        mImageLoader = ImageLoader.getInstance();
        options = YSUtils.displayImageOptions();

        this.refreshUI();

    }

    private void addListener() {

        kucunbiaoLayout.setOnClickListener(this);
//        image1Layout.setOnClickListener(this);
//        image2Layout.setOnClickListener(this);
//        image3Layout.setOnClickListener(this);
        postButton.setOnClickListener(this);
        saveButton.setOnClickListener(this);
//        xianhuoLayout.setOnClickListener(this);
        channelLayout.setOnClickListener(this);
        cityLayout.setOnClickListener(this);
        selectTemplateView.setOnClickListener(this);

    }

    private void refreshUI() {
        companyTV.setText(YSUser.instance().getCompany());
        contactTV.setText(YSUser.instance().getNickname());
        phoneTV.setText(YSUser.instance().getPhone());
        if (template == null) return;

        companyTV.setText(template.getCompany());
        contactTV.setText(template.getContact());
        phoneTV.setText(template.getTel());
//        xianhuoTV.setText( Integer.parseInt(template.getType()) == 0 ? "现货":"采购");
        channelTV.setText( template.getChannelname());
        nameTV.setText( template.getProductname());
//        caizhiTV.setText( template.getQuality());
//        guigeTV.setText( template.getSpecification());
//        priceTV.setText( template.getPrice());
//        quantityTV.setText( template.getNumber());
//        factoryTV.setText( template.getFactory());
        cityTV.setText( template.getPlace());
//        storehouseTV.setText( template.getStorehouse());
//        companyDesTV.setText( template.getCompanymark());
//        compayURLTV.setText( template.getCompanylink());
//        commentTV.setText( template.getMark());

        mImageLoader.displayImage(template.getKucunpic(), (ImageView) findViewById(R.id.imageView0));
//        mImageLoader.displayImage(template.getProductpic(), (ImageView) findViewById(R.id.imageView1));
//        mImageLoader.displayImage(template.getProductpic1(), (ImageView) findViewById(R.id.imageView2));
//        mImageLoader.displayImage(template.getProductpic2(), (ImageView) findViewById(R.id.imageView3));

        model.setType(template.getType());
        model.setKucunpic(template.getKucunpic());
//        model.setProductpic(template.getProductpic());
//        model.setProductpic1(template.getProductpic1());
//        model.setProductpic2(template.getProductpic2());

    }

    private void initViews(){
        companyTV = (EditText)findViewById(R.id.companyTV);
        contactTV = (EditText)findViewById(R.id.contactTV);
        phoneTV = (EditText)findViewById(R.id.phoneTV);
//        xianhuoTV = (TextView)findViewById(R.id.xianhuoTV);
        channelTV = (TextView)findViewById(R.id.channelTV);
        nameTV = (TextView)findViewById(R.id.nameTV);
//        caizhiTV = (EditText)findViewById(R.id.caizhiTV);
//        guigeTV = (EditText)findViewById(R.id.guigeTV);
//        priceTV = (EditText)findViewById(R.id.priceTV);
//        quantityTV = (EditText)findViewById(R.id.quantityTV);
//        factoryTV = (EditText)findViewById(R.id.factoryTV);
        cityTV = (TextView)findViewById(R.id.cityTV);
//        storehouseTV = (EditText)findViewById(R.id.storehouseTV);
//        companyDesTV = (EditText)findViewById(R.id.companyDesTV);
//        compayURLTV = (EditText)findViewById(R.id.compayURLTV);
//        commentTV = (EditText)findViewById(R.id.commentTV);
        kucunbiaoLayout = (RelativeLayout) findViewById(R.id.kucunbiaoLayout);
//        image1Layout = (RelativeLayout)findViewById(R.id.image1Layout);
//        image2Layout = (RelativeLayout)findViewById(R.id.image2Layout);
//        image3Layout = (RelativeLayout)findViewById(R.id.image3Layout);


//        xianhuoLayout = (RelativeLayout)findViewById(R.id.xianhuoLayout);
        channelLayout = (RelativeLayout)findViewById(R.id.channelLayout);
        cityLayout = (RelativeLayout)findViewById(R.id.cityLayout);

        postButton = (Button)findViewById(R.id.postBTN);
        saveButton = (Button)findViewById(R.id.saveBTN);
        selectTemplateView = (RelativeLayout)findViewById(R.id.selectTemplateBTN);

        advertiseLayout = (View)findViewById(R.id.advertiseLayout);
        advertiseET = (EditText) findViewById(R.id.advertiseET);
    }

    private void postXianhuo() {

        Map<String,String> params = this.collectInfo();
        if (params == null) return;
        this.saveTemplate();
        new YSRequest(this).POST(YSRequest.XIANHUO_POST, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess == YSRequest.REQUEST_OK){

                    runOnUiThread(new Runnable() {      // UI thread
                        @Override
                        public void run() {
                            new AlertDialog.Builder(PostXianhuoActivity.this).setTitle("提示")//设置对话框标题

                                    .setMessage("发布成功，请您耐心等待审核结果，可以在\"我的发布\"页面查看审核进度")//设置显示的内容 ;
                                    .setPositiveButton("我知道了",new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                            finish();
                                        }
                                    }).show();//在按键响应事件中显示此对话框
                        }
                    });
                }
            }
        });

    }

    private void saveTemplate() {
        Map<String,String> params = this.collectInfo();
        if (params == null) return;
        new YSRequest(this).POST(YSRequest.XIANHUO_TEMPLATE_ADD, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess == YSRequest.REQUEST_OK){

                    runOnUiThread(new Runnable() {      // UI thread
                        @Override
                        public void run() {
                            new AlertDialog.Builder(PostXianhuoActivity.this).setTitle("提示")//设置对话框标题

                                    .setMessage("成功保存为模板！")//设置显示的内容 ;
                                    .setPositiveButton("我知道了",new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                        }
                                    }).show();//在按键响应事件中显示此对话框
                        }
                    });
                }
            }
        });
    }

    private Map collectInfo(){
        List requiredList = new ArrayList();
        requiredList.add(companyTV);
        requiredList.add(contactTV);
        requiredList.add(phoneTV);
//        requiredList.add(caizhiTV);
//        requiredList.add(guigeTV);
//        requiredList.add(priceTV);
//        requiredList.add(factoryTV);
//        requiredList.add(storehouseTV);

        List requiredList2 = new ArrayList();
        requiredList2.add(cityTV);
        requiredList2.add(channelTV);

        for ( Object iView : requiredList ){
            if (((EditText) iView).getText().length() == 0) {
                YSUtils.showToastOn(this, ((EditText) iView).getHint().toString());
                return null;
            }
        }
        for ( Object iView : requiredList2 ){
            if(((TextView)iView).getText().length() == 0){
                YSUtils.showToastOn(this,((TextView)iView).getHint().toString());
                return null;
            }
        }

        model.setType("0");
        model.setCompany(companyTV.getText().toString());
        model.setContact(contactTV.getText().toString());
        model.setTel(phoneTV.getText().toString());
//        model.setType();
        model.setChannelname(channelTV.getText().toString());
        model.setProductname(nameTV.getText().toString());
//        model.setQuality(caizhiTV.getText().toString());
//        model.setSpecification(guigeTV.getText().toString());
//        model.setPrice(priceTV.getText().toString());
//        model.setNumber(quantityTV.getText().toString());
        model.setFactory("");
        model.setPlace(cityTV.getText().toString());
        model.setStorehouse("");
//        model.setCompanymark(companyDesTV.getText().toString());
//        model.setCompanylink(compayURLTV.getText().toString());
//        model.setMark(commentTV.getText().toString());
        model.setUserid(YSUser.instance().getUid());
        model.setAdvert(advertiseET.getText().toString());
        Map params = model.serialize();
//        HashMap params = new HashMap();
//        params.put("user", string);
        return params;
    }

    @Override
    public void onClick(View view) {
        int code = 0;
        if (view == kucunbiaoLayout){
            code = 0;
        }
//        else if(view == image1Layout){
//            code = 1;
//
//        }else if(view == image2Layout){
//            code = 2;
//
//        }else if(view == image3Layout){
//            code = 3;
//
//        }
        else if(view == postButton){
            postXianhuo();
            return;
        }else if(view == saveButton){
            saveTemplate();
            return;
        }else if(view == xianhuoLayout){
            enterTypeChoose();
            return;
        }else if(view == channelLayout){
            enterChannelChoose();
            return;
        }else if(view == cityLayout){
            enterCityChoose();
            return;
        }else if(view == selectTemplateView){
            enterTemplates();
            return;
        }

        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(false)
                .start(this, PhotoPicker.REQUEST_CODE + code);
    }

    private void enterTemplates() {
        Intent intent = new Intent();
        intent.putExtra("selectionMode","true");
        intent.setClass(this, XianhuoTemplateActivity.class);
        startActivityForResult(intent,XianhuoTemplateActivity.REQUEST_CODE);
    }

    private void enterCityChoose() {
        Intent intent = new Intent();
        intent.setClass(this, CityChooseActivity.class);
        startActivityForResult(intent,CityChooseActivity.REQUEST_CODE);
    }

    private void enterChannelChoose() {
        Intent intent = new Intent();
        intent.setClass(this, KuaixunSubscribeActivity.class);
        intent.putExtra("selection",true);
        startActivityForResult(intent,KuaixunSubscribeActivity.REQUEST_CODE);
    }

    private void enterTypeChoose() {
        Intent intent = new Intent();
        intent.setClass(this, SelectionListActivity.class);
        startActivityForResult(intent,SelectionListActivity.REQUEST_CODE);
    }

    private void uploadImage(String photoPath, final int imgCode ) {

        Bitmap img = BitmapFactory.decodeFile(photoPath);
        Bitmap newimg = null;
        float w = img.getWidth();
        float h = img.getHeight();
        if (w <= 900 || h <= 1200){
            newimg = img;
        }else if( w/h < 0.75 ){
            newimg = Bitmap.createScaledBitmap(img, (int)(1200 * w/h), 1200, true);
        }else {
            newimg = Bitmap.createScaledBitmap(img, 900, (int)(900*h/w), true);
        }
        this.postButton.setBackgroundColor(YSUtils.getColor(R.color.colorPrimaryDark,this));
        this.saveButton.setBackgroundColor(YSUtils.getColor(R.color.colorPrimaryDark,this));

        this.postButton.setEnabled(false);
        this.saveButton.setEnabled(false);

        new YSRequest(this).uploadImg2(photoPath,newimg, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode json) {
//                {"code":1,"result":"{\"img\":\"http://60.205.225.113/pictureService/showImage.action?type=0&filename=5a0313c5-9f3e-4788-8e25-c7d60f3e9fda.png\"}","msg":"上传成功"}
                ObjectMapper mapper = new ObjectMapper();
                try {
                    JsonNode resultNode = mapper.readTree(json.textValue());
                    JsonNode imgNode = resultNode.get("img");
                    if (imgNode != null){

                        String avatarUrl = imgNode.asText();
                        updateImage(avatarUrl,imgCode);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    reenableButton();
                }
            }
        });
    }

    private void updateImage(final String avatarUrl, final int imgCode) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ImageView imgView = null;
                if (imgCode == 0){
                    model.setKucunpic(avatarUrl);
                    imgView = (ImageView) findViewById(R.id.imageView0);
                }
//                else if(imgCode == 1){
//                    model.setProductpic(avatarUrl);
//                    imgView = (ImageView) findViewById(R.id.imageView1);
//
//                }else if (imgCode == 2){
//                    model.setProductpic1(avatarUrl);
//                    imgView = (ImageView) findViewById(R.id.imageView2);
//                }else if (imgCode == 3){
//                    model.setProductpic2(avatarUrl);
//                    imgView = (ImageView) findViewById(R.id.imageView3);
//                }
                mImageLoader.displayImage(avatarUrl, imgView);
            }
        });
    }

    private void reenableButton() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                postButton.setEnabled(true);
                postButton.setBackgroundColor(YSUtils.getColor(R.color.colorPrimary, PostXianhuoActivity.this));

                saveButton.setEnabled(true);
                saveButton.setBackgroundColor(YSUtils.getColor(R.color.colorPrimary, PostXianhuoActivity.this));

            }
        });
    }


    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK
                && requestCode >= PhotoPicker.REQUEST_CODE
                && requestCode <= PhotoPicker.REQUEST_CODE +3) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                String photoPath = photos.get(0);
                this.uploadImage(photoPath , requestCode - PhotoPicker.REQUEST_CODE);
            }
        }else if(resultCode == RESULT_OK
                && requestCode == CityChooseActivity.REQUEST_CODE){
                cityTV.setText(data.getStringExtra("data")) ;
        }else if(resultCode == RESULT_OK
                && requestCode == SelectionListActivity.REQUEST_CODE){
//            String typeString = data.getStringExtra("data");
//            xianhuoTV.setText(typeString) ;
//            model.setType("现货".equalsIgnoreCase(typeString)?"0":"1");
        }else if(resultCode == RESULT_OK
                && requestCode == KuaixunSubscribeActivity.REQUEST_CODE){
            channelTV.setText(data.getStringExtra("data")) ;

        }else if(resultCode == RESULT_OK
                && requestCode == XianhuoTemplateActivity.REQUEST_CODE){
            String string = data.getStringExtra("data");
            ObjectMapper mapper = new ObjectMapper();
            try {
                template = mapper.readValue(string, Xianhuo.class);
                refreshUI();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
